package com.xique.blelock.view.AcountManager;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.clj.fastble.utils.HexUtil;
import com.ivin.crop.Log;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.xique.blelock.Adapter.FingerAdapter;
import com.xique.blelock.Adapter.UserAdapter;
import com.xique.blelock.Interface.BleListenData;
import com.xique.blelock.NetUtils.NetResult;
import com.xique.blelock.NetUtils.XqNetClient;
import com.xique.blelock.R;
import com.xique.blelock.Utils.ACache;
import com.xique.blelock.Utils.BleUtils;
import com.xique.blelock.Utils.Stringkey;
import com.xique.blelock.Utils.TimeUtil;
import com.xique.blelock.model.FingerInfo;
import com.xique.blelock.model.LockAllinfo;
import com.xique.blelock.model.UserInfo;
import com.xique.blelock.model.UserOfLockinfo;
import com.xique.blelock.model.UserRole;
import com.xique.blelock.view.BaseActivity;
import com.xique.blelock.view.Thtreepackage.CountDownButtonHelper;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2018/12/11.
 */

public class FingerListActivty extends BaseActivity implements BleListenData {



    @BindView(R.id.title)
    TextView titile;


    private List<FingerInfo> fingerInfoList;

    //锁的相关信息
    private LockAllinfo lockAllinfo;

    @BindView(R.id.RecyclerView)
    SwipeMenuRecyclerView recyclerView;

    private FingerAdapter fingerAdapter;

    //管理员是1号，负管理员是可以是任何号，要看设置 kan order

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fingerlistlayout);
        ButterKnife.bind(this);
        initView();
        initRecyView();

    }

    protected void initView() {
        titile.setText("指纹列表");

        //获取指纹列表
//        getFingerList();

        lockAllinfo = (LockAllinfo) ACache.get(this).getAsObject(Stringkey.lockAllinfo);
        //从串口读取指纹列表

        fingerInfoList = lockAllinfo.getLockFpList();
        if(fingerInfoList.size() == 0){
            showToast(this, "暂时没有指纹列表");
        }

        getFingerDataFromUart();

    }

    private String testceont = "[{\n" +
            "\t\t\"feature\": \"\",\n" +
            "\t\t\"menunum\": 0,\n" +
            "\t\t\"nickname\": \"哈哈\",\n" +
            "\t\t\"order\": 1,\n" +
            "\t\t\"role\": 0,\n" +
            "\t\t\"time\": 1546225580000,\n" +
            "\t\t\"uid\": \"\"\n" +
            "\t},\n" +
            "\t{\n" +
            "\t\t\"feature\": \"\",\n" +
            "\t\t\"menunum\": 0,\n" +
            "\t\t\"nickname\": \"一样一样\",\n" +
            "\t\t\"order\": 2,\n" +
            "\t\t\"role\": 0,\n" +
            "\t\t\"time\": 1546225580000,\n" +
            "\t\t\"uid\": \"\"\n" +
            "\t},\n" +
            "\t{\n" +
            "\t\t\"feature\": \"\",\n" +
            "\t\t\"menunum\": 0,\n" +
            "\t\t\"nickname\": \"工行哈哈\",\n" +
            "\t\t\"order\": 3,\n" +
            "\t\t\"role\": 0,\n" +
            "\t\t\"time\": 1546225580000,\n" +
            "\t\t\"uid\": \"\"\n" +
            "\t}\n" +
            "]";
    @Override
    protected void onResume() {
        super.onResume();
        BleUtils.setBleListen(this);
    }
    private void initRecyView() {
        // 设置监听器。
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DefaultItemDecoration(ContextCompat.getColor(this, R.color.divider_primary)));

//        recyclerView.setSwipeItemClickListener(mItemClickListener);
        recyclerView.setSwipeMenuCreator(swipeMenuCreator);
        recyclerView.setSwipeMenuItemClickListener(mMenuItemClickListener);

        fingerAdapter = new FingerAdapter(fingerInfoList, lockAllinfo);
        recyclerView.setAdapter(fingerAdapter);

//        getUserList();
//        JSONArray jsonArray = JSONArray.parseArray(testceont);
//        fingerInfoList = jsonArray.toJavaList(FingerInfo.class);
        if(fingerInfoList.size() == 0){
            showToast(this, "暂时没有用户列表");
        }else{

            fingerAdapter.setDeviceList(fingerInfoList, lockAllinfo);
            fingerAdapter.notifyDataSetChanged();
        }
        Log.e("FingerListActivty负管理员是："+lockAllinfo.getSecondorder(), "");


    }

    /**
     * 菜单创建器，在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int position) {
            int width = getResources().getDimensionPixelSize(R.dimen.dp_70);
            int widthlarge = getResources().getDimensionPixelSize(R.dimen.dp_100);
            FingerInfo fingerInfo = fingerInfoList.get(position);

            // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
            // 2. 指定具体的高，比如80;
            // 3. WRAP_CONTENT，自身高度，不推荐;
            int height = ViewGroup.LayoutParams.MATCH_PARENT;


            // 添加右侧的，如果不添加，则右侧不会出现菜单。
            //检查是不是负管理员 这里的管理员操作权限主要是查看user的role

                //如果你是普通用户 没有任何权限
               if(lockAllinfo.getRole() == UserRole.root || ((lockAllinfo.getRole() == UserRole.secondroot) && (fingerInfo.getOrder() != FingerInfo.RootRole)))//管理员不能取消超级管理员
               {
                    //再继续判断自己是不是超级管理员
                    String admin = "";
                    if(fingerInfo.getOrder() == lockAllinfo.getSecondorder()){//当前负管理员的指纹
                        admin = "取消管理员";
                    }else{
                        //
                        //如果当前没有副指纹，就把他设置问指纹
                        if(!fingerInfoList.contains(new FingerInfo(lockAllinfo.getSecondorder())) && (fingerInfo.getOrder() != FingerInfo.RootRole)){
                            admin = "设置管理员";
                        }
                    }

                //副管理员只能编辑2到100的指纹编号
                    SwipeMenuItem addItem = new SwipeMenuItem(FingerListActivty.this).setBackground(R.color.coloblueAY)
                            .setText("编辑")
                            .setTextColor(Color.WHITE)
                            .setWidth(width)
                            .setHeight(height);
                    swipeRightMenu.addMenuItem(addItem); // 添加菜单到右侧。



                if(!TextUtils.isEmpty(admin)) {
                    SwipeMenuItem addItemadmin = new SwipeMenuItem(FingerListActivty.this).setBackground(R.color.green_pressed)
                            .setText(admin)
                            .setTextColor(Color.WHITE)
                            .setWidth(widthlarge)
                            .setHeight(height);
                    swipeRightMenu.addMenuItem(addItemadmin); // 添加菜单到右侧。
                    fingerInfoList.get(position).setMenunum(3);
                }else{
                    fingerInfoList.get(position).setMenunum(2);
                }
                SwipeMenuItem deleteItem = new SwipeMenuItem(FingerListActivty.this).setBackground(R.drawable.selector_red)
//                        .setImage(R.mipmap.ic_action_delete)
                        .setText("删除")
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);

                swipeRightMenu.addMenuItem(deleteItem);// 添加菜单到右侧。


            }
        }
    };

    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private SwipeMenuItemClickListener mMenuItemClickListener = new SwipeMenuItemClickListener() {
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge, int position) {
            menuBridge.closeMenu();

            int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
            int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。


            if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
                //Toast.makeText(FingerListActivty.this, "list第" + position + "; 右侧菜单第" + menuPosition, Toast.LENGTH_SHORT)
                        //.show();
                if(menuPosition  == 1 && (fingerInfoList.get(position).getMenunum() ==3))
                {
                    if(fingerInfoList.get(position).getOrder() == lockAllinfo.getSecondorder()){
                        setAdminRole(false, fingerInfoList.get(position));
                    }else{
                        setAdminRole(true, fingerInfoList.get(position));
                    }
                }else if(menuPosition  == 1 && (fingerInfoList.get(position).getMenunum() ==2)){
                    showdeletDialog(position);
                }
                else if(menuPosition == 2){//准备删除该用户，从设备里解除绑定关系,管理员才有这个权限
                    showdeletDialog(position);
                }else if(menuPosition == 0){//编辑指纹信息的名称
                    showEditname(position);
                }
            } else if (direction == SwipeMenuRecyclerView.LEFT_DIRECTION) {
                Toast.makeText(FingerListActivty.this, "list第" + position + "; 左侧菜单第" + menuPosition, Toast.LENGTH_SHORT)
                        .show();
            }
        }
    };

    private void showEditname(final int position) {


        new MaterialDialog.Builder(FingerListActivty.this)
                .title("修改名字")// 标题
                .inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PERSON_NAME)// 输入类型

                .input("请输入需要改的名字", "", new MaterialDialog.InputCallback() {
                    @Override
                    public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                        //Toast.makeText(FingerListActivty.this, "do something...", Toast.LENGTH_SHORT).show();

                    }
                })
                .negativeText("取消")
                .negativeColor(getResources().getColor(R.color.grey))
                .positiveText("确定")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if(TextUtils.isEmpty(dialog.getInputEditText().getText())){
                            showToast(FingerListActivty.this,"请输入名字");
                            return;
                        }
                        updateFingerName(position, dialog.getInputEditText().getText().toString());
                    }
                })
                .show(
                );// 显示对话框

    }

    private void updateFingerName(int position, String nickname) {
        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();

        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("lockId", BleUtils.getBleDevice().getMac().replace(":", ""));//E0:4C:63:6D:82:43
            jsonobject.put("nickName", nickname);
            jsonobject.put("order", fingerInfoList.get(position).getOrder());
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        showProgressDialog();
        netClient.updateFinger(jsonobject.toString()).enqueue(new Callback<NetResult>() {//获取验证码
            @Override
            public void onResponse(Call<NetResult> call, Response<NetResult> response) {
                hideProgressDialog();
                Log.e("删除用户信息=== "+response, "");
                if(response.body().isSuccess()){
                    showToast(FingerListActivty.this, "更新名称成功");
                    getFingerList();
                    //设备上也需要删除指纹
                }else {
                    showToast(FingerListActivty.this, "更新名称失败");
                }

            }

            @Override
            public void onFailure(Call<NetResult> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();

            }
        });
    }

    //提示是否需要删除  解除锁和用户的绑定关系
    protected void showdeletDialog(final int position) {

        new MaterialDialog.Builder(this)
                .title("提示")// 标题
                .titleColor(getResources().getColor(R.color.tipstitle))
                .content("确定要删除吗？")// 内容
                .contentColor(Color.BLACK)// 内容颜色
                .positiveText("确定")
                .positiveColorRes(R.color.cologbtnhou)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                        deletfinger2dev(fingerInfoList.get(position));
                    }
                })
                .negativeText("取消")
                .negativeColorRes(R.color.cancle)
                .show();

    }




    //删除指纹列表
    private void deletFingerlist(final List<FingerInfo> fingerInfoList) {
        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();

        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("lockId", BleUtils.getBleDevice().getMac().replace(":", ""));//E0:4C:63:6D:82:43
            jsonobject.put("lockFpList", com.alibaba.fastjson.JSONObject.toJSONString(fingerInfoList));
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        showProgressDialog();
        netClient.deletFingerLisst(jsonobject.toString()).enqueue(new Callback<NetResult>() {//获取验证码
            @Override
            public void onResponse(Call<NetResult> call, Response<NetResult> response) {
                hideProgressDialog();
                Log.e("删除用户信息=== "+response, "");
                if(response.body().isSuccess()){
                    showToast(FingerListActivty.this, "删除指纹成功");

                    getFingerList();

                }else {
                    showToast(FingerListActivty.this, "删除指纹失败");
                }

            }

            @Override
            public void onFailure(Call<NetResult> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();

            }
        });
    }



    private void setAdminRole(boolean setadmin, FingerInfo userOfLockinfo){

        if(setadmin)
        {
            BleUtils.sendData(Stringkey.setAdmin + HexUtil.encodeHexStr(new byte[]{(byte) userOfLockinfo.getOrder()}));
        }else{
            BleUtils.sendData(Stringkey.cancleAdmin + HexUtil.encodeHexStr(new byte[]{(byte) userOfLockinfo.getOrder()}));
        }


    }
    private Callback<NetResult>  netResultCall = new Callback<NetResult>() {
        @Override
        public void onResponse(Call<NetResult> call, Response<NetResult> response) {
            hideProgressDialog();
            Log.e("获取用户信息Useroflock=== "+ response, "");
            if(response.body().isSuccess()){
                showToast(FingerListActivty.this, "设置管理员成功 ");
                getFingerList();
            }else {
                showToast(FingerListActivty.this, "设置管理员失败");
            }

        }

        @Override
        public void onFailure(Call<NetResult> call, Throwable t) {
            t.printStackTrace();
            hideProgressDialog();

        }
    };


    //从服务器获取指纹列表
    private void getFingerList() {

                XqNetClient netClient =  new XqNetClient();
                JSONObject jsonobject = new JSONObject();

                try {
                    jsonobject.put("token", userInfo.getToken());
                    jsonobject.put("uid", userInfo.getUid());
                    jsonobject.put("lockId", BleUtils.getBleDevice().getMac().replace(":", ""));//E0:4C:63:6D:82:43
                    jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                showProgressDialog();
                netClient.getFigerList(jsonobject.toString()).enqueue(new Callback<NetResult<List<FingerInfo>>>() {//获取验证码
                    @Override
                    public void onResponse(Call<NetResult<List<FingerInfo>>> call, Response<NetResult<List<FingerInfo>>> response) {


                            if(response.body().isSuccess()){
                                fingerInfoList = response.body().getData();
                                Log.e("fingers=== "+ JSON.toJSONString(fingerInfoList), "");
                                fingerAdapter.setDeviceList(fingerInfoList, lockAllinfo);
                                fingerAdapter.notifyDataSetChanged();
                                lockAllinfo.setLockFpList(fingerInfoList);
                                ACache.get(FingerListActivty.this).put(Stringkey.lockAllinfo, lockAllinfo);
                            }else {
                                showToast(FingerListActivty.this, "没有获取到指纹列表");
                            }
                            hideProgressDialog();
                    }

                    @Override
                    public void onFailure(Call<NetResult<List<FingerInfo>>> call, Throwable t) {
                        t.printStackTrace();
                        hideProgressDialog();

                    }
                });

    }


    @OnClick(R.id.BACKER)
    public void BackLastPage(){
        finish();
    }

    private void deletFinger2Dev(List<FingerInfo> userOfLockinfo) {
//        BleUtils.sendData(Stringkey.deletFingerHead+ HexUtil.encodeHexStr(new byte[]{(byte) userOfLockinfo.getOrder()}));

    }
    private void getFingerDataFromUart() {
        BleUtils.sendData(Stringkey.getFingerList);
    }

    private void deletfinger2dev(FingerInfo fingerInfo) {
        BleUtils.sendData(Stringkey.deletFingerHead + HexUtil.encodeHexStr(new byte[]{(byte) fingerInfo.getOrder()}));
    }


    @Override
    public void didReciveData(byte[] data) {
            Log.e("获取指纹列表"+ HexUtil.encodeHexStr(data), "");

            String rep = HexUtil.encodeHexStr(data);
            if(rep.startsWith(Stringkey.getFingerList) && data.length == 14){//同步指纹列表
                //判断有没有新的之心信息，有的话需要更新到服务器去
                List<FingerInfo> neworderlist = new ArrayList<>();

                //还有记录删除的，如果设备端没有的指纹，服务端有那么需要从服务端删除
                List<FingerInfo> allFingerlist = new ArrayList<>();
                //把十六进制转化为二进制字符串

                for(int index = 2; index<data.length; index++){
                    byte temp = data[index];
                    for(int index2=0; index2<8; index2++){
                        if(((0xff&temp) & (1 << index2) ) != 0){
                            //这里需要判断服务是否已经存在改指纹信息
                            FingerInfo fingerInfo = new FingerInfo((index-2)*8+index2);
                            if(!fingerInfoList.contains(fingerInfo)){
                                neworderlist.add(fingerInfo);
                            }
                            allFingerlist.add(fingerInfo);
                        }
                    }

                }
                //这里判断是否有新的order
                if(neworderlist.size()>0){
                    addFingerList(neworderlist);
                }
                List<FingerInfo> needdeletfingerInfoList = new ArrayList<>();
                //  遍历一遍看看多余的需要删除
                for(FingerInfo finger: fingerInfoList) {
                    if(!allFingerlist.contains(finger)){
                        needdeletfingerInfoList.add(finger);
                    }
                }
                if(needdeletfingerInfoList.size() > 0){
                    deletFingerlist(needdeletfingerInfoList);//同步发现设备没有的指纹需要从服务端删除
                }


            }else if(rep.startsWith(Stringkey.setAdmin)){//同步管理员
                lockAllinfo.setSecondorder(data[2]);//当前没有指纹副管理员
                ACache.get(FingerListActivty.this).put(Stringkey.lockAllinfo, lockAllinfo);
                showToast(this,"设置成功");
//                getFingerList();
                fingerAdapter.notifyDataSetChanged();
            }else if(rep.startsWith(Stringkey.cancleAdmin)){
                lockAllinfo.setSecondorder(0);//当前没有指纹副管理员
                showToast(this,"已经取消");
                ACache.get(FingerListActivty.this).put(Stringkey.lockAllinfo, lockAllinfo);
                fingerAdapter.notifyDataSetChanged();
//                getFingerList();
            }else if(rep.startsWith(Stringkey.deletFingerHead)){
                List<FingerInfo> fingerInfoList = new ArrayList<>();
                fingerInfoList.add(new FingerInfo(data[2]));
                deletFingerlist(fingerInfoList);//点击删除场景
            }
    }


    //添加指纹列表
    private void addFingerList(final List<FingerInfo> neworderlist){
        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();

        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("lockId", BleUtils.getBleDevice().getMac().replace(":", ""));//E0:4C:63:6D:82:43
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
            jsonobject.put("lockFpList", com.alibaba.fastjson.JSONObject.toJSONString(neworderlist));

        } catch (JSONException e) {
            e.printStackTrace();
        }

        showProgressDialog();
        netClient.addFingerList(jsonobject.toString()).enqueue(new Callback<NetResult>() {//获取验证码
            @Override
            public void onResponse(Call<NetResult> call, Response<NetResult> response) {
                hideProgressDialog();

                Log.e("addFingerList=== "+ response, "");
                if(response.body().isSuccess()){
                    if(neworderlist.get(0).getOrder() == lockAllinfo.getSecondorder()){
//                        lockAllinfo.setSecondorder(0);//清楚负管理员
                        ACache.get(FingerListActivty.this).put(Stringkey.lockAllinfo, lockAllinfo);
                    }
                    getFingerList();
                }else {
                    showToast(FingerListActivty.this, "没有获取到指纹列表");
                }

            }

            @Override
            public void onFailure(Call<NetResult> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();

            }
        });

    }
}
